<template>
    <div class="custom-page">
      <iframe :src="url" class="custom-iframe" frameborder="0" />
    </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
import { LAYOUT_PLAN_KEY } from '@/constant'

const url = ref('')
const frame = ref<HTMLIFrameElement | null>(null)

const syncToken = (targetUrl: string) => {
    return new Promise(resolve => {
        const appUser = JSON.parse(localStorage.getItem('app-user'))
        const userInfo = JSON.parse(localStorage.getItem('al__USER_INFO'))

        const message = {
            appId: {
                value: appUser.appid,
                expire: userInfo.expire
            },
            uid: {
                value: appUser.uuid,
                expire: userInfo.expire
            },
            productId: {
                value: appUser.productId,
                expire: userInfo.expire
            },
            token: {
                value: appUser.token,
                expire: userInfo.expire
            },
            userInfo: userInfo
        }

        let frame = document.createElement('iframe')
        frame.style.position = 'absolute'
        frame.style.top = '-9999px'
        frame.style.left = '-9999px'
        frame.style.width = '1px'
        frame.style.height = '1px'
        frame.name = 'syncTokenFrame' + new Date().getTime()

        // 超时不做任何处理
        let timer = setTimeout(() => {
            resolve('timeout')
        }, 3000)

        let child: Window | null = null
        frame.onload = () => {
            child = frame.contentWindow
            setTimeout(() => {
                child?.postMessage(message, '*')
                setTimeout(() => {
                    resolve('ok')
                    clearTimeout(timer)
                }, 3)
            })
        }
        frame.setAttribute('src', targetUrl)
        document.body.appendChild(frame)
    })
}

watch(
    () => route,
    newVal => {
        const { query } = newVal
        // 如果可以通过router拿到url，则直接使用
        if (query && query.iframe_url) {
            const { iframe_url, ...otherQuery } = query
            const queryArr = []
            for (const key in otherQuery) {
              if (otherQuery[key] && otherQuery[key].indexOf(LAYOUT_PLAN_KEY) > -1) {
                queryArr.push(`${key}=${otherQuery[key].split(LAYOUT_PLAN_KEY)[0]}`)
              } else {
                queryArr.push(`${key}=${otherQuery[key]}`)
              }
            }
            let tmpUrl = ''
            // 处理布局方式
            if (iframe_url.indexOf(LAYOUT_PLAN_KEY) > -1) {
              tmpUrl = iframe_url.split(LAYOUT_PLAN_KEY)[0]
            }
            // 处理url中没有:的问题
            if (iframe_url.match(/^https\/\/.*$/)) {
              tmpUrl = iframe_url.replace(/^https\/\//g, 'https://')
            } else if (iframe_url.match(/^http\/\/.*$/)) {
              tmpUrl = iframe_url.replace(/^http\/\//g, 'http://')
            }

            if (iframe_url.indexOf('?') > -1) {
              tmpUrl = `${iframe_url}&${queryArr.join('&')}`
            } else if (queryArr.length > 0) {
              tmpUrl = `${iframe_url}?${queryArr.join('&')}`
            } else {
              tmpUrl = `${iframe_url}`
            }
            syncToken(tmpUrl).then(() => {
              url.value = tmpUrl
            })
            return
          }

      // 因为生成代码是整体将URL注册到路由中，又因为嵌入的iframe路由模式多，因此此处采用整个url分割方式获取嵌入页面URL
        let { href } = location
        const SPLIT_KEY = 'customPage?iframe_url='

        if (href.indexOf(LAYOUT_PLAN_KEY) > -1) {
          href = href.split(LAYOUT_PLAN_KEY)[0]
        }
        const hrefArray = href.split(SPLIT_KEY)
        hrefArray.shift()
        //通过split整合后的数组，获取url
        const targetUrl = hrefArray.join(SPLIT_KEY)
        let tmpUrl = ''
        //url在地址栏中会抹掉:,下两个循环为增加:
        if (targetUrl.match(/^https\/\/.*$/)) {
          tmpUrl = targetUrl.replace(/^https\/\//g, 'https://')
        } else if (targetUrl.match(/^http\/\/.*$/)) {
          tmpUrl = targetUrl.replace(/^http\/\//g, 'http://')
        } else {
            // 没有输入协议的情况
            tmpUrl = 'http://' + targetUrl
        }

        syncToken(tmpUrl).then(() => {
            url.value = tmpUrl
        })
    },
    {
        immediate: true,
        deep: true
    }
)
</script>

<style lang="less" scoped>
.custom-page {
    height: 100%;
    width: 100%;
    .custom-iframe {
        height: 100%;
        width: 100%;
    }
}
</style>
